<template>
  <div class="task-manager">
    <h1>任务管理器</h1>
    <table>
      <thead>
      <tr>
        <th>PID ({{ processList.length }})</th>
        <th>名称</th>
        <th>CPU ({{ totalCpuRate }}%)</th>
        <th>内存 ({{ totalMemoryRate }}%)</th>
        <th>路径</th>
      </tr>
      </thead>
      <tbody>
      <tr v-if="isSearchHasResult">
        <td
            rowspan="{{ processList.length }}" colspan="5" class="no-data">没有可显示的进程信息
        </td>
      </tr>
      <tr v-else
          v-for="process in processList" :key="process.pid"   @contextmenu="onContextMenu($event ,process)">
        <td>{{ process.pid }}</td>
        <td>{{ process.binName }}</td>
        <td>{{ process.cpuUsage }}%</td>
        <td>{{ process.memoryUsage }}%</td>
        <td>{{ process.binPath }}</td>
      </tr>

      </tbody>

    </table>
  </div>
</template>

<script lang="ts">
import {invoke} from '@tauri-apps/api/core';

import {computed, onMounted, onUnmounted, reactive, ref, UnwrapRef, watch} from 'vue';
import {provide, inject} from "vue";
import {useSearchStore} from "../store/SearchResult.ts";
import ContextMenu from "@imengyu/vue3-context-menu";


const processBinName = ref<string[]>([]);
const processPids = ref<number[]>([]);
const pidsCpuUsage = ref<number[]>([]);
const processMemoryUsage = ref<number[]>([]);
const processBinPath = ref<string[]>([]);
const isSearchHasResult = ref(false)


async function getProcessBinName(pids: UnwrapRef<Number[]>) {
  try {
    processBinName.value = await invoke('get_windows_process_names', {pids});
  } catch (error) {
    console.error('Failed to get process bin name:', error);
  }
}

async function getProcessPids() {
  try {
    processPids.value = await invoke('get_process_pids');
  } catch (error) {
    console.error('Failed to get process pids:', error);
  }
}


async function getProcessCpuUsage(value: UnwrapRef<Number[]>) {
  try {
    pidsCpuUsage.value = await invoke('get_process_cpu_usage', {pids: value});
  } catch (error) {
    console.error('Failed to get process cpu usage:', error);
  }
}

async function getProcessMemoryUsage(value: UnwrapRef<Number[]>) {
  try {
    processMemoryUsage.value = await invoke('get_process_memory_usage', {pids: value});
  } catch (error) {
    console.error('Failed to get process memory usage:', error);
  }
}

async function getProcessBinPath(value: UnwrapRef<Number[]>) {
  try {
    processBinPath.value = await invoke('get_process_path', {pids: value});
  } catch (error) {
    console.error('Failed to get process bin path:', error);
  }
}

// 组件挂载时执行

export default {
  name: 'TaskManager',

  setup() {
    const searchStore = useSearchStore();

    function onContextMenu(e: MouseEvent , process :any ) {
      e.preventDefault();
      ContextMenu.showContextMenu({
        x: e.x,
        y: e.y,
        theme: 'mac dark',
        items: [
          {
            label: "结束任务" ,
            onClick: async ( event ) =>  {
              await invoke('kill_specific_process', {pid: process.pid})
               processList.value = processList.value.filter((item) => item.pid !== process.pid)
            }
          }, {
            label: "属性"
          }, {
            divided: true,
            icon: "icon-reload-1",
            label: "打开文件所在位置"
            ,onClick: async ( event ) =>  {
               await invoke('open_specific_process_directory', {path: process.binPath})

            }
          }
        ]
      });
    }

    let processList = ref<any[]>([]);

    // 监听 searchResult 变化，更新 processList
    watch(() => searchStore.searchResult, (newValue) => {
      console.log("searchResult change", searchStore.searchResult)
      if (newValue === null || newValue === undefined || newValue.trim() === "") {startInterval() ;}
       else  {stopInterval();  searchHandleProcess(newValue.trim()); }

    })
    let temp = ref([]);
// 定义 intervalId
    const intervalId = ref<number | null>(null);

    function searchHandleProcess(searchValue: string) {
      processList.value = temp.value;
      console.log( "start  searchHandleProcess ", searchValue)
      if (searchValue !== null && searchValue !== undefined && searchValue.trim() !== '') {

        processList.value = processList.value.filter((item) => {
          return item.binName?.includes(searchValue) ||
              item.binPath?.includes(searchValue)
        })
      }
    }

    async function updateProcessList() {
      await getProcessPids();
      await getProcessBinName(processPids.value);
      await getProcessCpuUsage(processPids.value);
      await getProcessMemoryUsage(processPids.value);
      await getProcessBinPath(processPids.value);

      // 更新 processList
      processList.value = processPids.value.map((pid, index) => ({
        binName: processBinName.value[index],
        pid: processPids.value[index],
        cpuUsage: pidsCpuUsage.value[index]?.toFixed(2),
        memoryUsage: processMemoryUsage.value[index]?.toFixed(2),
        binPath: processBinPath.value[index],
      }));
      processList.value.sort((a, b) => a.cpuUsage - a.cpuUsage);
      temp.value = processList.value;
    };
    const totalCpuRate = computed(() => {
      return pidsCpuUsage.value?.reduce((acc , cur ) => acc + cur, 0).toFixed(2)
    })
    const totalMemoryRate = computed(() => {
      return processMemoryUsage.value?.reduce((acc, cur ) => acc + cur, 0).toFixed(2);
    })
    function startInterval() {
      if (intervalId.value === null) {
        intervalId.value = window.setInterval(updateProcessList, 2000);
      }
    }

    function stopInterval() {
      if (intervalId.value !== null) {
        clearInterval(intervalId.value);
        intervalId.value = null;
      }
    }


    // 组件挂载时启动定时器
    onMounted(() => {
      updateProcessList(); // 立即更新一次数据
      if (searchStore.searchResult === null || searchStore.searchResult === undefined || searchStore.searchResult.trim() === "") {
        startInterval();
      }
    });

    // 组件卸载时清除定时器
    onUnmounted(() => {
      stopInterval();
    });


    return {
      processList, processPids, processBinName, processBinPath, processMemoryUsage, pidsCpuUsage
      , totalMemoryRate, totalCpuRate, isSearchHasResult , onContextMenu
    };
  }

}
</script>

<style scoped>
.task-manager {
  font-family: Arial, sans-serif;
  display: flex;
  flex-direction: column;
  align-items: start;
  justify-content: start;
  font-size: small;
  color: lightpink;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 8px;
  text-align: left;
  border-bottom: 1px solid gray;
}

th {
  background-color: transparent;
}
</style>z